<template>  
<el-card>
	<template #header>
		<el-space wrap>
			
			<mdp-select style="width:100%" :disabled="categoryType" v-model="filters.categoryType" item-code="categoryType"  placeholder="请选择主题" clearable @change="onCategoryTypeChange"/> 
			<el-button icon="plus" type="primary" plain  @click.prevent.stop="addTopNode()" title="添加顶级分类，在分类上右键可以添加子分类"/>
			<el-button v-if="showConfirm"  type="warning"  @click="confirm" title="确认选择" icon="check"/>   
			<el-input v-model="filters.key" placeholder="名称"/>
		</el-space>
	</template>
 <el-tree accordion v-if="show"
	:props="defaultTreeProps"
	:filter-node-method="filterNode"
	:show-checkbox="showCheckbox"
	:default-expand-all="defaultExpandAll"
	:expand-on-click-node="expandOnClickNode"
	:node-key="nodeKey_"
	:default-expanded-keys="defaultExpandedKeys"
	:default-checked-keys="defaultCheckedKeys"
	auto-expand-parent
	@check-change="handleCheckChange"
	@current-change="handleCurrentChange"
	@node-click="handleNodeClick" 
	:check-strictly="true"
	:check-on-click-node="true"
	lazy
	:load="loadNode"
	ref="nodeTree" @contextmenu.prevent>
	<template  #default="{ node, data}">
		<div class="custom-tree-node" @contextmenu.prevent title="右键可以增删改">
			<el-popover
				:open-delay="1000"
				placement="top-start" 
				:width="showConfirm?300:200"
				trigger="contextmenu" >
				
				<el-button icon="plus" circle type="success" v-if=" !(!data.id || data.id=='C0'||data.id=='0')" @click.prevent.stop="addNode(data,node)" title="添加子分类"/>
				<el-button icon="edit" circle type="warning" v-if=" !(!data.id || data.id=='C0'||data.id=='0')" @click.prevent.stop="editNode(data,node)" title="修改名字"/>
				<el-button icon="delete" circle type="danger" v-if=" !(!data.id || data.id=='C0'||data.id=='0')" @click.prevent.stop="deleteNode(data,node)" title="删除该分类"/> 

				<template #reference><div style="display:flex;align-items:center;width:100%;"><Icon v-if="data.imageUrls" :icon="data.imageUrls"/>{{data.name}}</div></template>
			</el-popover> 
		</div> 
	</template>
</el-tree>
</el-card>
<el-dialog
	title="新增分类"
	v-model="addVisible"
	width="60%" append-to-body>
		<el-form ref="addCategory" :model="addCategory" label-width="200" 	>
			<el-form-item label="主题"  prop="categoryType" :rules="[
				{ required: true, message: '主题不能为空'}
				]">
				<mdp-select v-model="addCategory.categoryType" :disabled="currentCategory?.categoryType" item-code="categoryType" placeholder="请选择主题"/> 
			</el-form-item>
			
			<el-form-item label="上级分类">
				
				<el-tag>{{  currentCategory && currentCategory.id && currentCategory.id!='C0'? "上级："+currentCategory.name:"顶级分类C0" }}</el-tag>

			</el-form-item>
			<el-form-item label="分类编号">
				<el-input v-model="addCategory.id" placeholder="如果为空，则系统自动生成"/>
			</el-form-item>
			<el-form-item label="分类名称"  prop="name"
			:rules="[
				{ required: true, message: '名称不能为空'}
				]">
				<el-input v-model="addCategory.name" />
			</el-form-item>

			<el-form-item label="图标" >
				  <IconSelect v-model="addCategory.imageUrls"/>
			</el-form-item> 

			<el-form-item label="配置" prop="name">
				<el-checkbox v-model="addCategory.isLeaf" auto-complete="off"  true-label="0" false-label="1">是否可添加子分类</el-checkbox>

				<el-checkbox v-model="addCategory.limitType" auto-complete="off"  true-label="1" false-label="2">文章数目是否限制为1篇</el-checkbox>

				<el-checkbox v-model="addCategory.isAuth" auto-complete="off" true-label="1" false-label="0">文章发布是否需要审核</el-checkbox>
			</el-form-item> 
			<el-form-item label="权限" >
				<el-radio v-model="addCategory.qxLvl" auto-complete="off"  label="0">全网公开</el-radio>
				<el-radio v-model="addCategory.qxLvl" auto-complete="off"  label="1">内部公开</el-radio>
				<el-radio v-model="addCategory.qxLvl" auto-complete="off"  label="2">受限</el-radio> 
				<el-checkbox v-model="addCategory.pqx" auto-complete="off"  true-label="1" false-label="0">所有子类遵守上级权限规则</el-checkbox> 
			</el-form-item> 
		</el-form>
		
		<template #footer>
			<el-button @click="addVisible = false">关闭</el-button>
			<el-button type="primary" v-loading="addLoading"  @click="addCategorySubmit">确 定</el-button>
		</template>
</el-dialog>

<el-dialog
	title="修改分类提示"
	v-model="editVisible"
	width="60%" append-to-body>
		<el-form ref="editCategory" :model="editCategory" label-width="200" 	>
			<el-form-item label="主题"  prop="categoryType" :rules="[
				{ required: true, message: '主题不能为空'}
				]">
				<mdp-select v-model="editCategory.categoryType" item-code="categoryType" placeholder="请选择主题" :disabled="editCategory.categoryType"/> 
			</el-form-item>
			<el-form-item label="分类编号"  prop="id">
				{{editCategory.id}}
			</el-form-item>
			<el-form-item label="分类名称"  prop="name"
			:rules="[
				{ required: true, message: '名称不能为空'}
				]">
				<el-input v-model="editCategory.name" />
			</el-form-item>


			<el-form-item label="图标" >
				  <IconSelect v-model="editCategory.imageUrls"/>
			</el-form-item> 
			<el-form-item label="配置" >
				<el-checkbox v-model="editCategory.isLeaf" auto-complete="off"  true-label="0" false-label="1">是否可添加子分类</el-checkbox>

				<el-checkbox v-model="editCategory.limitType" auto-complete="off"  true-label="1" false-label="2">文章数目是否限制为1篇</el-checkbox>

				<el-checkbox v-model="editCategory.isAuth" auto-complete="off" true-label="1" false-label="0">文章发布是否需要审核</el-checkbox>
			</el-form-item> 
			

			<el-form-item label="权限" >
				<el-radio v-model="editCategory.qxLvl" auto-complete="off"  label="0">全网公开</el-radio>
				<el-radio v-model="editCategory.qxLvl" auto-complete="off"  label="1">内部公开</el-radio>
				<el-radio v-model="editCategory.qxLvl" auto-complete="off"  label="2">受限</el-radio> 
				<el-button type="primary" v-if="editCategory.qxLvl=='2'" @click="$refs['qxSetDialog'].open({category:editCategory})">配置限制规则</el-button>
				<el-checkbox v-model="editCategory.pqx" auto-complete="off"  true-label="1" false-label="0">所有子类遵守上级权限规则</el-checkbox> 
			</el-form-item> 
		</el-form>
		
		<template #footer>
			<el-button @click="editVisible = false">关 闭</el-button>
			<el-button type="primary" v-loading="editLoading" @click="editCategorySubmit">确 定</el-button>
		</template>
</el-dialog>
<mdp-dialog ref="qxSetDialog">
	<template #default="{visible,data,dialog}">
		<category-qx-set :visible="visible" :category="data.category" @close="dialog.close()" @submit="dialog.close()"/>
	</template>
</mdp-dialog> 
</template>

<script> 
	
import { mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user'
import CategoryQxSet from './QxSet.vue';
	export default {
		components:{
			CategoryQxSet
		},
		watch: {
	      nodeFilterText(val) {
	        this.$refs.nodeTree.filter(val);
	      },
	      checkedKeys(val){
	      	 this.$refs.nodeTree.setCheckedKeys(val);
	      },
	      refresh(val){ 
	      },
	      currentKey(val){
	    	  this.$refs.nodeTree.setCheckedKeys([val]);
		  },
		  value(val){
		  	this.nodeid=val;
		  },
		  nodeid(val){
		  	this.$emit('input',val);
		  },
		  categoryType(val){  
				//this.$refs.nodeTree.filter(this.filters.categoryType)
		  },
		  'filters.categoryType'(){
				this.getTreeData();
			},
		  'filters.key'(v){
				this.$refs.nodeTree.filter(v)
			}
	    },
	    computed:{

			categoryTreeData() { 
				return []
			},
	    	defaultExpandedKeys(){
	    		return this.defaultCheckedKeys;
	    	},
	    	defaultCheckedKeys(){
	    		if(this.value){
	    			return [this.value];
	    		}
	    		return this.checkedKeys;
	    	},
	    	nodeKey_(){
	    		return this.nodeKey?this.nodeKey:'id'
	    	},
			   ...mapState(useUserStore,[
					'userInfo'
				  ]),
	    },
		props:{
			'value':String,Array,
			'branchId':String,
			'visible':{type:Boolean,default:false},
			'showCount':{type:Boolean,default:false},
			'showRoot':{type:Boolean,default:false},
			'countTips':String,
			'showFilter':{type:Boolean,default:false},
			'multiple':{type:Boolean,default:false},
			'checkedKeys':Array,
			'refresh':{type:Boolean,default:false},
			'defaultExpandAll':{type:Boolean,default:false},
			'expandOnClickNode':{type:Boolean,default:false},
			showCheckbox:{type:Boolean,default:false},
			showConfirm:{type:Boolean,default:false},
			'indent':Number,
			categoryType:{type:String,default:null}, 
			nodeKey:String,
			/**
			 * 上级分类
			 */
			pid:{
				type:String,
				default:''
			},
			crelyType:{
				type:String,
				default:''
			},
			crelyId:{
				type:String,
				default:''
			},
			crelyStype:{
				type:String,
				default:'',
			},
			crelySid:{
				type:String,
				default:''
			}
		},
 		data() {
			return {
				filters:{
					categoryType:'',
				},
				nodeFilterText: '',
				treeData:[],
				defaultTreeProps:{

					id:this.nodeKey==null?'id':this.nodeKey,
					label:'name',
					children: 'children', 
					isLeaf: function(n){
						return n.childNum<=0
					}
				},
				listLoading: false,
				addLoading:false,
				editLoading:false,
				nodeid:'',
				currentCategory:{id:'',pid:'',name:'',categoryType:null},
				addCategory:{id:'',pid:'',name:'',isLeaf:'0',isAuth:'0',limitType:'2',categoryType:'',pqx:'',qxLvl:''},
				editCategory:{id:'',pid:'',name:'',isLeaf:'0',isAuth:'0',limitType:'2',categoryType:'',pqx:'',qxLvl:''},
				addVisible:false,
				editVisible:false,
				options:{categoryType:[]},
				root:{},
				isAddTop:false,
				resolve:null,
				
				show:true,
			}
		},
		methods: {
			onCategoryTypeChange(v){
				this.getTreeData()
			}, 
			unselect(){
				this.$refs['nodeTree'].setCurrentKey(null)
			},
			handleCheckChange(data, checked, indeterminate) {
				let checkedKeys=this.$refs.nodeTree.getCheckedKeys();
				console.log(this.multiple);
				if( this.multiple===undefined || this.multiple===false||this.multiple==='false'){
					if(checked==true){
						if(checkedKeys.length>1){
							this.$refs.nodeTree.setCheckedKeys([data[this.nodeKey_]]);
							this.$emit('check-change',data,checked,indeterminate);
							this.nodeid=data[this.nodeKey_];
						}else{
							this.$emit('check-change',data,checked,indeterminate);
							this.nodeid=data[this.nodeKey_];
						}
					}else{
						if(checkedKeys.length==0){
							this.nodeid='';
							this.$emit('check-change',data,checked,indeterminate);
						}
					}
				}else{
					this.$emit('check-change',data,checked,indeterminate);
				}
		    },
			handleCurrentChange(data, node) {
		    	this.$emit('current-change',data, node);
		    },
		    handleNodeClick(data, node, comp) {
				this.$emit('node-click',data, node, comp);
			},
			handleAddCategoryClose(){
				this.addVisible=false;
			},
			addCategorySubmit(){
				var branchId=this.userInfo.branchId
				var pid=""
				if(this.isAddTop){
					pid="C0"
				}else{
					pid=this.currentCategory.id
					branchId=this.currentCategory.branchId
				}
				this.addCategory.pid=pid
				this.addCategory.isShow='1'
				this.addCategory.branchId=branchId 
				if(this.crelyType){
					this.addCategory.crelyType=this.crelyType
				}
				
				if(this.crelyId){
					this.addCategory.crelyId=this.crelyId
				}
				
				if(this.crelyStype){
					this.addCategory.crelyStype=this.crelyStype
				}
				
				if(this.crelySid){
					this.addCategory.crelySid=this.crelySid
				}
				this.$refs.addCategory.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							this.$mdp.addCategory(this.addCategory).then(res=>{
								this.addLoading=false;
								if(res.tips.isOk){
									

									this.$message.success(res.tips.msg); 
									if(!this.isAddTop){
										if(this.currentCategory.children){
											this.currentCategory.children.push(res.data)
										}else{
											this.currentCategory.children=[res.data]
										}
									}else{
										this.$refs['nodeTree'].append(res.data,this.root)
									}
									
									this.addVisible=false;
								}else{
									this.$message.error(res.tips.msg);
								}
							}).catch(e=>this.addLoading = false  );

						});
					}
				});

			},

			editCategorySubmit(){
				this.$refs.editCategory.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							this.$mdp.editCategory(this.editCategory).then(res=>{
								//console.log("res--"+JSON.stringify(res));
								this.editLoading = false;
								if(res.tips.isOk){
									this.editVisible=false;
									this.$message.success(res.tips.msg); 
									
									this.$refs['nodeTree'].updateKeyChildren(res.data.id,res.data)
									this.editVisible=false
								}else{
									this.$message.error(res.tips.msg);
								}
							}).catch(e=>this.editLoading = false  );

						});
					}
				});

			},
			addTopNode(){
				this.isAddTop=true 
				this.addVisible=true;
				this.addCategory.categoryType=this.categoryType||null
				return false;
			},
		    addNode(data, node, comp) {
					this.isAddTop=false
				this.currentCategory=data
				this.addVisible=true;
				this.addCategory.categoryType=this.currentCategory?.categoryType||null
				return false;
			},
		    editNode(data, node, comp) {
				this.editCategory=data
				this.editVisible=true;
				console.log("editNode__"+JSON.stringify(data));
				return false;
		    },
		    deleteNode(data, node, comp) {
				console.log("deleteNode__"+JSON.stringify(data));
						if(data.children){
							this.$message.error("请先删除子元素");
							return;
						}
						let params={
							id:data.id,
							branchId:data.branchId
						}
						if(!params.branchId){
							params.branchId=this.userInfo.branchId
						}
						this.$confirm('确认删除吗？', '提示', {}).then(() => {
							this.$mdp.delCategory(params).then(res=>{
								//console.log("res--"+JSON.stringify(res));
								if(res.tips.isOk){
									this.editVisible=false; 
									
									this.$refs['nodeTree'].remove(data)
									this.$message.success(res.tips.msg); 
								}else{
									this.$message.error(res.tips.msg);
								}
							});
						})
					return false;
		    },
			//获取分类树列表
			getTreeData(refresh) {  
				this.show=false
				this.$nextTick(()=>{
					this.show=true
				})
			},

		 refreshNode(guid) { 
        let node = this.$refs.nodeTree.getNode(guid)
        if (node && node.loaded) {
            node.loaded = false
            node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
        } 
			},
			filterNode(value, data) { 
		        if (!value) return true; 
		        return data.name.includes(value); 
		     },
		     renderContent(h, { node, data, store }) {
				var countMsg=''; 
				if(this.countTips){
					countMsg=this.countTips;
				}
				if(this.showCount==true || this.showCount=='true'){
					return h('div'[h('span',node.label+"("+data.count+countMsg+")")]) ;
				}else{
					return h('div',[h('span',node.label+"("+data.count+countMsg+")")]) ;
					//return h('span',"@contextmenu.prevent='contextmenu('"+node.id+"')',"+node.label+"("+(data.children==null?0:data.children.length)+countMsg+")") ;
				}

			  },
			 
			
			confirm(){
				   var nodes= this.$refs.nodeTree.getCheckedNodes(false,false)
				   if(this.multiple){
					this.$emit('confirm',nodes)
				   }else{
					this.$emit('confirm',nodes&&nodes.length>0?nodes[0]:null)
				   }
				   
				},
				setNodeData(data){
					if(!data){
						return;
					}
					if(data.imageUrls){
						return;
					}
					data.imageUrls=data.childNum>0?'fa-solid:folder':'fa:file-o'
				},
				loadNode(node, resolve) {  
					  if (node.level === 0) {
							
						  this.root=node
						  this.resolve=resolve
						  let params = {
							  'pid':'C0'
						  };
						  if(this.categoryType){
								params.categoryType=this.categoryType
							}
							if(this.filters.categoryType){
								params.categoryType=this.filters.categoryType
							}
						  this.listLoading = true;
						  this.$mdp.listCategory(params).then((res) => {
							  var tips=res.tips;
							  var data=res.data;
							  this.listLoading = false; 
							  this.expandRowKeys=data.map(i=>i.deptid)
								data.forEach(k=>this.setNodeData(k))
							  resolve(data )
  
						  }).catch(() => {
							  this.listLoading = false;
						  });
					  }else  {
							  setTimeout(() => {
								  let params = {
									  pid:node.data.id
								  }; 
								  this.listLoading = true;
								  this.$mdp.listCategory(params).then((res) => {
									  var tips=res.tips;
									  var data=res.data;
									  this.listLoading = false;
										
										data.forEach(k=>this.setNodeData(k))
									  resolve(data)
  
								  }).catch(() => {
									  this.listLoading = false;
								  });
							  }, 500);
  
					  }
				  }
		},
		mounted() {
			this.nodeid=this.value; 
		}
	}

</script>

<style rel="stylesheet/scss" lang="scss" scoped>


  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #4386c6;

  }

  .el-ic {
    display: none;
    i, span {
      padding: 0 1px;
      font-size: 18px;
      font-weight: 600;
    }
  }


  .el-tree-node__content:hover .el-ic {
    color: #428bca !important;
    display: inline-block;
	margin-left: 2px; 
	z-index: 10000;
  }

  .el-tree-node__content:hover {
    font-weight: bold;
  }

  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content :hover {
    .el-tree-node__expand-icon.is-leaf {
      color: transparent;
      cursor: default;
    }
    /*background-color: #3998d9;*/
    .custom-tree-node {
      font-weight: bold;
    }
    .el-tree-node__expand-icon {
      font-weight: bold;
    }

  }

</style>
